package com.ai.sevice.advertising;

import com.ai.common.enums.ConfigModuleEnum;
import com.ai.common.utils.CommonUtil;
import com.ai.common.utils.ConfigUtil;
import com.ai.dao.entity.ai.AiUser;
import com.ai.dao.entity.ai.AiUserOperatingRecord;
import com.ai.repository.ai.AiUserOperatingRecordRepository;
import com.ai.repository.ai.AiUserRepository;
import com.ai.sevice.advertising.request.IsShowAdvertisingRequest;
import com.ai.sevice.advertising.request.WatchVideoRequest;
import com.ai.sevice.advertising.response.IsShowAdvertisingResponse;
import com.ai.sevice.advertising.response.WatchVideoResponse;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class AdvertisingService {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private AiUserRepository aiUserRepository;

    @Autowired
    private AiUserOperatingRecordRepository aiUserOperatingRecordRepository;

    /**
     * 是否展示广告
     * @param request
     * @return
     */
    public IsShowAdvertisingResponse isShowAdvertising(String uid,IsShowAdvertisingRequest request) {
        IsShowAdvertisingResponse response = new IsShowAdvertisingResponse();
        //超级管理员不用看广告
        String superAdmin = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.DEFAULT.getModule(), "superAdmin");
        if (StringUtils.isNotBlank(superAdmin)) {
            String[] superAdminArr = superAdmin.split(",");
            List<String> superAdminList = new ArrayList<>(superAdminArr.length);
            //数组转list
            Collections.addAll(superAdminList, superAdminArr);
            if (superAdminList.contains(uid)){
                response.setIsShowAdvertising(false);
                return response;
            }
        }

        response.setIsShowAdvertising(false);
        String isShowAdvertising = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.advertising.getModule(), "isShowAdvertising");
        if (isShowAdvertising != null && isShowAdvertising.equals("true")){
            response.setIsShowAdvertising(true);
        }
        return response;
    }

    /**
     * 是否可观看广告视频
     * @return
     */
    public WatchVideoResponse isWatchVideo(String uid) {
        WatchVideoResponse response = new WatchVideoResponse();
        response.setCode(1);
        List<String> unlimitedAdvertisingList = ConfigUtil.getInstance().getConfigList(ConfigModuleEnum.advertising.getModule(), "unlimitedAdvertising");
        if (CollectionUtils.isNotEmpty(unlimitedAdvertisingList) && unlimitedAdvertisingList.contains(uid)){
            response.setCode(0);
            return response;
        }

        String watchVideoCount = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.advertising.getModule(), "watchVideoCount");
        if (StringUtils.isBlank(watchVideoCount)){
            watchVideoCount = "0";
        }
        String bucket = "watchVideoBucket-" + uid + "-" + CommonUtil.getNowDateStr();
        RBucket<Integer> watchVideoBucket = redissonClient.getBucket(bucket);
        if (watchVideoBucket != null && watchVideoBucket.get() != null && watchVideoBucket.get() >= Integer.parseInt(watchVideoCount)){
            //log.warn("isWatchVideo 今天观看广告次数已达上限，请明天再来观看！ -> uid:" + uid + " bucket:" + bucket);
            response.setMsg("今天观看广告次数已达上限，请明天再来观看！");
            return response;
        }
        response.setCode(0);
        return response;
    }

    /**
     * 观看广告视频
     * @return
     */
    public synchronized WatchVideoResponse watchVideo(String uid, WatchVideoRequest request) {
        WatchVideoResponse response = new WatchVideoResponse();
        response.setCode(1);

        String watchVideoCount = "0";
        List<String> unlimitedAdvertisingList = ConfigUtil.getInstance().getConfigList(ConfigModuleEnum.advertising.getModule(), "unlimitedAdvertising");
        if (CollectionUtils.isNotEmpty(unlimitedAdvertisingList) && unlimitedAdvertisingList.contains(uid)){
            watchVideoCount = "500";
        }else {
            String watchVideoCountConfig = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.advertising.getModule(), "watchVideoCount");
            if (StringUtils.isNotBlank(watchVideoCountConfig)) {
                watchVideoCount = watchVideoCountConfig;
            }
        }

        String bucket = "watchVideoBucket-" + uid + "-" + CommonUtil.getNowDateStr();
        RBucket<Integer> watchVideoBucket = redissonClient.getBucket(bucket);
        if (watchVideoBucket != null && watchVideoBucket.get() != null && watchVideoBucket.get() >= Integer.parseInt(watchVideoCount)){
            log.warn("今天观看广告次数已达上限，请明天再来观看！ -> uid:" + uid + " bucket:" + bucket + " request ->  " + JSON.toJSONString(request));
            response.setMsg("今天观看广告次数已达上限，请明天再来观看！");
            return response;
        }
        Integer count = watchVideoBucket.get();
        if (count == null){
            count = 0;
        }
        AiUser aiUser = aiUserRepository.getUserByUid(uid);
        if (aiUser != null) {
            //给看广告视频用户新增积分
            int integral = 3;
            String watchVideoAdd = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.integral.getModule(), "watchVideoAdd");
            if (StringUtils.isNotBlank(watchVideoAdd)) {
                integral = Integer.parseInt(watchVideoAdd);
            }
//            if (aiUser.getIntegral() > 5000){
//                log.warn("看广告视频更新权益失败 -> uid:" + uid + " 原因 ->  积分大于5000 request —> " + JSON.toJSONString(request));
//                return response;
//            }
            aiUser.setIntegral(aiUser.getIntegral() + integral);
            int update = aiUserRepository.updateByPrimaryKeySelective(aiUser);
            if (update <= 0){
                log.warn("看广告视频更新权益失败 -> uid:" + uid + " request ->  " + JSON.toJSONString(request));
            }
            //保存记录
            insertOrUpdateAiUserOperatingRecord(uid);
            response.setCode(0);
            watchVideoBucket.set(count + 1,1, TimeUnit.DAYS);
        }
        return response;
    }

    private void insertOrUpdateAiUserOperatingRecord(String uid) {
        if (StringUtils.isBlank(uid)){
            return;
        }
        RLock lock = redissonClient.getLock("insertOrUpdateAiUserOperatingRecord-" + uid);
        try {
            lock.lock();
            AiUserOperatingRecord aiUserOperatingRecord = aiUserOperatingRecordRepository.getAiUserOperatingRecord(1,uid, CommonUtil.getNowDateStr());
            if (aiUserOperatingRecord != null){
                aiUserOperatingRecord.setCount(aiUserOperatingRecord.getCount() + 1);
                aiUserOperatingRecordRepository.updateByPrimaryKeySelective(aiUserOperatingRecord);
            }else{
                aiUserOperatingRecord = new AiUserOperatingRecord();
                aiUserOperatingRecord.setUid(uid);
                aiUserOperatingRecord.setType(1);
                aiUserOperatingRecord.setCount(1);
                aiUserOperatingRecord.setDateStr(CommonUtil.getNowDateStr());
                aiUserOperatingRecordRepository.insertSelective(aiUserOperatingRecord);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }finally {
            lock.unlock();
        }
    }
}
